package com.base.controller;

import com.base.comm.CommContent;
import com.base.po.voip.*;
import com.base.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class update_RebateOrder {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private UsersService usersService;
	@Autowired
	private SubscribersService subscribersService;
	@Autowired
	private RebateOrdersService rebateOrdersService;
	@Autowired
	private ShopOrderService shopOrderService;
	@Autowired
	private RebateDisService rebateDisService;
	
	String SUCCESS = "success";

	// 更改淘宝订单用户
	@RequestMapping(value = "/updateRebateOrder", method = RequestMethod.POST)
	public void updateRebateOrder(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id,  String upmobile) throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		Users users = usersService.selectByPrimaryKey(adminUserId);
		// 代理商id
		String pId = null;
		if (adminUsergrade == 0){
			out.print("admin无法修改");
			return;
		}
		if (adminUsergrade == 1){
			pId = users.getId();
		}
		if (adminUsergrade == 2){
			pId = users.getParentid();
		}

		RebateOrders rebateOrders = rebateOrdersService.selectByPrimaryKey(id);

		List<Subscribers> subList = subscribersService.selectBySub(upmobile, pId);
		int code = 0;
		if (subList != null && subList.size() > 0){
			// 获取用户信息
			Subscribers sub = subList.get(0);
			BigDecimal ratio = new BigDecimal(1); // 一级分润 默认0
			BigDecimal sper = new BigDecimal(1); // 二级分润 默认1
			// 如果存在该用户
			if (sub != null) {
				// 如果该返利是返购物金 订单付款 充值购物金
				boolean flag = shopOrderService.selectByXgt2(sub.getId(), sub.getParentid(), rebateOrders.getNumIid()) >= 1;
				ShopOrder shopOrder = shopOrderService.selectByXgt(sub.getId(), sub.getParentid(), rebateOrders.getNumIid());
				if (shopOrder != null && rebateOrders.getTkStatus() == 3) {
					if (shopOrderService.updateByXgt(shopOrder.getId()) >= 1) {
						sub.setShopBalance(sub.getShopBalance() + (rebateOrders.getPayPrice().multiply(new BigDecimal(0.3))).intValue());
						subscribersService.updateByPrimaryKeySelective(sub);
					}
				}
				ratio = new BigDecimal(usersService.selectByPrimaryKey(users.getId()).getRebateratio()); // 获取一级佣金比例
				// 如果用户存在推荐人
				if (sub.getShareper() != null && !sub.getShareper().isEmpty()) {
					try {
						sper = new BigDecimal(usersService.selectByPrimaryKey(users.getId()).getRebateratio2()); // 获取二级佣金比例
					} catch (Exception e) {
						e.printStackTrace();
					}
					// 增加推荐人的可提现金额
					BigDecimal sSper = sper; // 获取二级比例
					RebateDis rd = new RebateDis(rebateOrders.getTradeId(), rebateOrders.getNumIid(), rebateOrders.getPictUrl(), rebateOrders.getItemTitle(), rebateOrders.getItemNum(), rebateOrders.getPrice(),
							rebateOrders.getAlipayTotalPrice(), rebateOrders.getCreateTime(), rebateOrders.getEarningTime(), rebateOrders.getTkStatus(), rebateOrders.getOrderType(), rebateOrders.getAlipayTotalPrice(),
							!flag ? rebateOrders.getIncomeRate().multiply(rebateOrders.getCommissionRate()).multiply(rebateOrders.getAlipayTotalPrice()).multiply(ratio).multiply(sSper) : new BigDecimal(0),
							flag, sub.getShareper(), sub.getId());
					if (rebateDisService.selectByPrimaryKey(rebateOrders.getTradeId()) == null) {
						rebateDisService.insertSelective(rd); // 新增
					} else {
						rebateDisService.updateByPrimaryKeySelective(rd); // 更新
					}

					// 推荐者拿去二级比率返利后 剩余的给购买者的比率
					ratio = ratio.multiply(new BigDecimal(1).subtract(sper));
				}
				rebateOrders.setUserCommission(!flag ? rebateOrders.getIncomeRate().multiply(rebateOrders.getCommissionRate()).multiply(rebateOrders.getAlipayTotalPrice()).multiply(ratio) : new BigDecimal(0)); // 分配给用户的佣金
				rebateOrders.setUserType(flag); // 用户提现状态
			}
			rebateOrders.setUserid(sub.getId());
			code = rebateOrdersService.updateByPrimaryKeySelective(rebateOrders);
		}else{
			out.print("未查询到该用户");
			return;
		}

		if (code == 1) {
			out.print(SUCCESS);
		} else {
			out.print("更改失败，请您重试");
		}
	}
}
